// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
/* jshint esversion: 6 */
window.getIps = "//api.mofing.com";

window.getIpwwws = "//www.mofing.com";

window.params = "?shop_id=2535611&uid=439124&token=bb97f5884c72a98a9ade4063cc86e0da";

import Vue from 'vue';
import App from './App';
import router from './router';
import FastClick from 'fastclick';
import axios from 'axios';
import qs from 'qs';
import jquery from 'jquery';
import Mint from 'mint-ui';
import 'mint-ui/lib/style.css';
import VueDND from 'awe-dnd';
import VueQuillEditor  from 'vue-quill-editor';
import './assets/font/iconfont.css';
//import BaiduMap from 'vue-baidu-map'
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import VueLazyLoad from 'vue-lazyload';
import "babel-polyfill";
import VueScroller from 'vue-scroller';


Vue.config.productionTip = false;
Vue.prototype.$axiosCK = axios; //全局axios配置
Vue.prototype.$qsCK = qs; //全局qs配置
Vue.prototype.$ = jquery; //全局jquery配置
//弹框
import  { AlertPlugin,Alert,ConfirmPlugin,LoadingPlugin,ToastPlugin} from 'vux';
Vue.use(VueLazyLoad,{

});
//取消移动端300ms的延迟
FastClick.attach(document.body);

Vue.use(AlertPlugin);
Vue.use(ConfirmPlugin);
Vue.use(LoadingPlugin);
Vue.use(ToastPlugin);
Vue.use(Mint);
Vue.use(VueDND);
Vue.use(VueQuillEditor);
Vue.use(VueScroller);
//Vue.use(BaiduMap,{
//	ak:'ZUmVaxN7zLX0bQAbMzB6G1EI4wU8qwHb'
//})

Vue.filter("filterTimes", function(val) {
	let y = new Date(val).getFullYear();
	let m = new Date(val).getMonth() + 1 >= 10 ? new Date(val).getMonth() + 1 : '0' + (new Date(val).getMonth() + 1);
	let d = new Date(val).getDate() >= 10 ? new Date(val).getDate() : '0' + new Date(val).getDate();
	return y + "-" + m + "-" + d;
});
Vue.filter("filterTimess", function(val) {
	let y = new Date(val).getFullYear();
	let m = new Date(val).getMonth() + 1 >= 10 ? new Date(val).getMonth() + 1 : '0' + (new Date(val).getMonth() + 1);
	let d = new Date(val).getDate() >= 10 ? new Date(val).getDate() : '0' + new Date(val).getDate();
	let h = new Date(val).getHours() >= 10 ? new Date(val).getHours() : '0' + new Date(val).getHours();
	let ms = new Date(val).getMinutes() >= 10 ? new Date(val).getMinutes() : '0' + new Date(val).getMinutes();
	let s = new Date(val).getSeconds() >= 10 ? new Date(val).getSeconds() : '0' + new Date(val).getSeconds();
	return y + "-" + m + "-" + d + " " + h + ":" + ms + ":" + s;
});
Vue.filter("filterTimesss", function(val) {
	let y = new Date(val).getFullYear();
	let m = new Date(val).getMonth() + 1 >= 10 ? new Date(val).getMonth() + 1 : '0' + (new Date(val).getMonth() + 1);
	let d = new Date(val).getDate() >= 10 ? new Date(val).getDate() : '0' + new Date(val).getDate();
	let h = new Date(val).getHours() >= 10 ? new Date(val).getHours() : '0' + new Date(val).getHours();
	let ms = new Date(val).getMinutes() >= 10 ? new Date(val).getMinutes() : '0' + new Date(val).getMinutes();
	return y + "-" + m + "-" + d + " " + h + ":" + ms;
});
//整数还是整数，小数保留2位小数（不四舍五入）
Vue.filter("twoDecimal",function(val){
	return Math.floor(val * 100) / 100;
});

function axiosPost(url, params, bool) {
	return new Promise((resolve, reject) => {
		axios({
			url: bool === true ? window.getIpwwws + url : window.getIps + url,
			method: 'post',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			data: qs.stringify(params)
		}).then(res => {
			resolve(res.data);
		}).catch((error) => {
			reject(error);
		});
	});
}

function axiosPostno(url, params) {
	return new Promise((resolve, reject) => {
		axios({
			url: window.getIpwwws + url ,
			method: 'post',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			data: qs.stringify(params)
		}).then(res => {
			resolve(res.data);
		}).catch((error) => {
			reject(error);
		});
	});
}
function axiosPostn(url, params) {
	return new Promise((resolve, reject) => {
		axios({
			url:  url ,
			method: 'post',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			data: qs.stringify(params)
		}).then(res => {
			resolve(res.data);
		}).catch((error) => {
			reject(error);
		});
	});
}

function axiosGet(url, params, bool) {
	return new Promise((resolve, reject) => {
		axios({
			url: bool === true ? window.getIpwwws + url : window.getIps + url,
			method: 'get',
			timeout:25000,
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			params
		}).then(res => {
			resolve(res.data);
		}).catch((error) => {
			reject(error);
		});
	});
}
function axiosGetno(url, params) {
	return new Promise((resolve, reject) => {
		axios({
			url:window.getIpwwws + url + window.params,
			method: 'get',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			params
		}).then(res => {
			resolve(res.data);
		}).catch((error) => {
			reject(error);
		});
	});
}
///wechat/joins/sharetoken/10000.json
function wxConfig(){
	axiosPostn('//www.mofing.com/wechat/joins/sharetoken/10000.json',{
		url:location.href.split('#')[0],
		from:2
	}).then( res => {
		wx.config({
		    beta: true,
		    debug: false,
		    appId: res.appId,
		    timestamp: res.timestamp,
		    nonceStr: res.nonceStr,
		    signature: res.signature,
		    jsApiList: [
				'checkJsApi',
				'openLocation',
				'getLocation',
				'hideMenuItems',
				'hideOptionMenu',
				'showOptionMenu',
				'closeWindow',
				'onMenuShareTimeline',
				'onMenuShareAppMessage',
				'onMenuShareQQ',
				'onMenuShareWeibo',
				'onMenuShareQZone',
				'chooseImage','previewImage','uploadImage'
		    ]
		});
	});
}
function wechatUploadImages(settings,previewCallBack,callBack,allCallBack){
	//settings  微信选图配置，
	//count每次最多允许选择的数量
	//sourceType 可以指定来源是相册还是相机，['album', 'camera']默认二者都有，可以只选择一个
	//previewCallBack 	单条选择完成之后，本地临时预览
	//callBack 			单条上传完成的回调方法，
	//allCallBack		所有文件上传完成的回调方法
	let _this=this;
	let defaultSettings={count: 1,sourceType: ['album', 'camera']};
	settings=settings || defaultSettings;
	//异步调用微信选择图片功能
	wx.chooseImage({
	    count: settings.count || defaultSettings.count, // 默认9
	    sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	    sourceType: settings.sourceType || defaultSettings.sourceType, // 拍照还是相册
	    success: function (res) {
		let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		let finishCount=0;
		let sumCount=localIds.length;
		let allData=[];
		_this.$.each(localIds, function(ind,localFileId) {
			setTimeout(function(){
				//本地临时预览回调方法
				if(previewCallBack){
					previewCallBack(localFileId);
				}
				//异步调用上传图片到微信服务器
				wx.uploadImage({
				    localId: localFileId, // 需要上传的图片的本地ID，由chooseImage接口获得
				    isShowProgressTips: 1, //强制增加loading
				    success: function (res) {
				    	// 返回图片的服务器端ID，只有成功才返回，失败没有处理方法
				        var serverId = res.serverId; 
				        //通过微信服务器返回的图片ID转换成我们的图片地址
				        _this.$.get(getIpwwws+"/wechat/images/formart.json",{
							"id":10000,
							"sourceid":serverId
						},function(data){
							//data返回数据结构
							/*{"code": 200,
								"data": {
									"url": "img\/weixin\/eZEvg13mljl_iRxDiEwKMklPMqtP_J2wW5-puvT3wCxIY_HpSFGYxlJZ66n095IX.jpg",
									"fullurl": "http:\/\/cdn6.mofing.com\/img\/weixin\/eZEvg13mljl_iRxDiEwKMklPMqtP_J2wW5-puvT3wCxIY_HpSFGYxlJZ66n095IX.jpg"
							}}*/
							if(data && data.code==200){
								allData.push(data.data);
								//只返回一条数据
								if(callBack){
									//1:返回data对象，
									//2:本地文件地址，可以用于当前页面预览显示，
									//3:当前图片顺序，
									//4:完成的顺序
									callBack(data.data,localFileId,ind,finishCount);							
								}
							}else{
								console.log("转换失败");
							}
							finishCount++;
							//不管成功与否，返回所有的数据
							if(finishCount>=sumCount && allCallBack){
								//返回所有data对象数组
								//2:本地文件地址数组，循环之后，可以用于当前页面预览显示
								allCallBack(allData,localIds);
							}
						});
				    }
				});
			},100);
		});
	    }
	});
}
//微信分享
function makeShare(title,desc,link,imgUrl){
	wx.onMenuShareTimeline({
		title :"【"+ title+"】"+desc,
		link : link,
		imgUrl : imgUrl,
		success : function() {
			console.log("分享成功");
		}
	});
	wx.onMenuShareAppMessage({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功");
		},
		cancel : function() {
			console.log("取消分享");
		}
	});
	wx.onMenuShareQQ({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功");
		},
		cancel : function() {
			console.log("取消分享");
		}
	});
	wx.onMenuShareWeibo({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功");
		},
		cancel : function() {
			console.log("取消分享");
		}
	});
	wx.onMenuShareQZone({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功");
		},
		cancel : function() {
			console.log("取消分享");
		}
	});
}
function closeWin(){
	let u = navigator.userAgent;
    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios
    if(isAndroid) {
        window.WebView.finish();    //安卓关闭浏览器
    } else if (isiOS) {
        window.location.href = 'mofing://exitbrowser';  //iOS关闭浏览器
    }	
}
/*
 * 统一支付
 * type 订单类型 1-balance 2-Alipay 3-Wechat
 * orderid 订单id
 * ordertype 订单类型
 * money 金额，只在充值或者转账时候用到
 */
function payOrder(type,orderid,ordertype,money){
	return new Promise(function(resolve, reject) {
		var _GLOBAL_ = 'web';
		var userAgentInfo = navigator.userAgent.toLowerCase();
		if(userAgentInfo.match(/MicroMessenger/i)=="micromessenger") {
			_GLOBAL_ = 'wechat';
		}else if(userAgentInfo.match(/MofingEYK/i)=="mofingeyk") {
			_GLOBAL_ = 'app';
		}else {
			_GLOBAL_ = 'web';
		}
	   var obj = {};
	   obj.payment = type;
	   obj.ordertype = ordertype;
	   obj.appid = 10000;
	   obj.id = orderid;
	   obj.buyerid = '';
	   obj.money = money;	   
	   if(_GLOBAL_ === 'wechat'){ 
			//客户端内部支付
			obj.paytype = 'js';
		}else if(_GLOBAL_ === 'web'){ 
			obj.paytype = 'native';
		}else{ //-------------------------------------------app-------------------------
			obj.paytype = 'app';
			//调用客户端支付接口，页面会呈现是否支付完成的按钮
			openAPI("payment",orderid,ordertype);
			reject();
			return;
		}	   
	   //支付接口,获取返回参数
	   axios({
			url: window.getIpwwws+'/payment/pays/create.json',
			method: 'post',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			data: qs.stringify(obj)
		}).then(res => {
			resolve(res.data);
		}).catch((error) => {
			reject(error);
		});	   	   
	});
}

function getPlatform(){
	var userAgentInfo = navigator.userAgent.toLowerCase();
	if(userAgentInfo.match(/MicroMessenger/i)=="micromessenger") {
		return 'wechat';
	}else if(userAgentInfo.match(/MofingEYK/i)=="mofingeyk") {
		return 'app';
	}else {
		return 'web';
	}
}

function andrOpenAPI(type,title,desc,imgUrl,linkUrl){
	window.exercise.call(
		"notefunction",
		type,
		title,
		desc,
		imgUrl,
		linkUrl					
	);
}
function iosOpenAPI(params){
	window.webkit.messageHandlers.MofingWKWebview.postMessage(params)
}
Vue.prototype.$axiosPost = axiosPost; //全局axiosPost配置----------交互就用这个足够
Vue.prototype.$axiosPostno = axiosPostno; //全局axiosPost配置----------交互就用这个足够
Vue.prototype.$axiosPostn = axiosPostn; //全局axiosPost配置----------交互就用这个足够
Vue.prototype.$axiosGet = axiosGet; //全局axiosGet配置
Vue.prototype.$axiosGetno = axiosGetno; //全局axiosGet配置
Vue.prototype.$wxConfig   = wxConfig; //全局微信配置
Vue.prototype.$wxUploadImg  =wechatUploadImages;//全局微信上传图片
Vue.prototype.$closeWin  = closeWin;//关闭浏览器
Vue.prototype.$makeShare  = makeShare;//微信分享
Vue.prototype.$payOrder = payOrder; //统一支付
Vue.prototype.$getPlatform = getPlatform; //获取平台
Vue.prototype.$andrOpenAPI= andrOpenAPI; //与安卓做交互，调用安卓api
Vue.prototype.$iosOpenAPI = iosOpenAPI; //与安卓做交互，调用安卓api

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
});
